﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyUserExtParameter : Parameter {
		/// <summary>
		/// 
		/// </summary>
		public string ExtId { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) {
			if (context.User == null) {
				return string.Empty;
			} else if (context.User.Identity == null) {
				return string.Empty;
			} else if (string.IsNullOrWhiteSpace(ExtId)) {
				return string.Empty;
			} else {
				var extIdArray = ExtId.Split(',', ' ')
					.Where(item => !string.IsNullOrWhiteSpace(item))
					.Select(item => Convert.ToInt32(item))
					.ToArray();

				if (extIdArray.Length == 0) {
					return string.Empty;
				} else if (extIdArray.Length == 1) {
					return context.GetUserExt(extIdArray[0]).FirstOrDefault();
				} else {
					return context.GetUserExt(extIdArray).ToArray();
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected override System.Web.UI.WebControls.Parameter Clone() {
			var ret = new MyUserExtParameter();
			ret.Name = Name;
			ret.Size = Size;
			ret.Type = Type;
			ret.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
			ret.DbType = DbType;
			ret.DefaultValue = DefaultValue;
			ret.Direction = Direction;

			ret.ExtId = ExtId;

			return ret;
		}
	} // end of MyUserParameter.
}
